package ui;

import java.text.NumberFormat;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JTextArea;

import race.ObservableList;
import race.Ranking;

public class RaceRankViewer extends JTextArea implements Observer {

	private static final long serialVersionUID = 1L;
	private ObservableList<Ranking> list;

	public RaceRankViewer(ObservableList<Ranking> list) {
		super();
		this.setEditable(false);
		this.list = list;
		this.list.addObserver(this);
	}

	@Override
	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
	 */
	public void update(Observable arg0, Object arg1) {
		this.setText("");
		for (int i = 0; i < list.getList().size(); i++) {
			this.insert(list.getList().get(i).getContender() + "      "
					+ fromStringToMilliseconds(list.getList().get(i).getTime())+" ms\n", this.getCaretPosition());
		}
	}

	private static String fromStringToMilliseconds(String string) {
		double delay = Double.parseDouble(string);
		delay = delay / 1000000;
		NumberFormat formatter = NumberFormat.getNumberInstance();
		formatter.setMinimumFractionDigits(3);
		formatter.setMaximumFractionDigits(3);
		return "" + formatter.format(delay);
	}

}
